﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Com.ZX.Manager;

namespace Com.ZX
{
	//// 1、提供遍历接口 2、key value 形式读取,索引器 3、提供send方法 4、sender 5 获取type name 6、content
	/// <summary>
	/// 
	/// </summary>
	public class Message : IEnumerable<KeyValuePair<string, object>>
	{
		private Dictionary<string, object> dicDatas = null;
		public string Name { get; private set; }
		public object Sender { get; private set; }
		public object Content { get; set; }
	
		#region 索引器
		/// <summary>
		/// 访问消息索引器
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public object this[string key]
		{
			get
			{
				if (dicDatas == null || !dicDatas.ContainsKey(key))
					return null;
				return dicDatas[key];
			}
			set
			{
				if (dicDatas == null)
					dicDatas = new Dictionary<string, object>();
				if (dicDatas.ContainsKey(key))
					dicDatas[key] = value;
				else
					dicDatas.Add(key, value);
			}
		}
		#endregion

		public Message(string name, object sender)
		{
			Name = name;
			Sender = sender;
		}

		public Message(string name,object sender,object content)
		{
			Name = name;
			Sender = sender;
			Content = content;
		}
		
		public Message(string name, object sender, object content,params object[] dicParams)
		{
			Name = name;
			Sender = sender;
			Content = content;
			if (dicParams.GetType() == dicDatas.GetType())
			{
				for (int i = 0; i < dicParams.Length; i++)
				{
					Dictionary<string, object> tempDic = (Dictionary<string, object>)dicParams[i];
					foreach (var item in tempDic)
					{
						this[item.Key] = item.Value;
					}
				}
			}
		}

		public Message(Message msg)
		{
			Name = msg.Name;
			Content = msg.Content;
			Sender = msg.Sender;
			foreach (var item in msg.dicDatas)
			{
				this[item.Key] = item.Value;
			}
		}
		public void Send()
		{
			//调用MsgManager.Send()相关
			MsgManager.inst.SendMessage(this);
		}

		public void Add(string key,object value)
		{
			this[key] = value;
		}

		public void Remove(string key)
		{
			if (dicDatas != null && dicDatas.ContainsKey(key))
				dicDatas.Remove(key);
		}

		public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
		{
			if (dicDatas == null)
				yield break ;
			foreach (var item in dicDatas)
			{
				yield return item;
			}
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return dicDatas.GetEnumerator();
		}
	}
}
